package com.fenxiangle.yueding.feature.order.view;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.entity.bo.EventEntity;
import com.fenxiangle.yueding.entity.bo.PublishDemandBo;
import com.fenxiangle.yueding.entity.bo.TabEntity;
import com.fenxiangle.yueding.entity.bo.TeamBo;
import com.fenxiangle.yueding.entity.bo.UnMsgBo;
import com.fenxiangle.yueding.entity.bo.UnReadCountBo;
import com.fenxiangle.yueding.entity.bo.UserImageBo;
import com.fenxiangle.yueding.feature.home.view.UserInfoActivity;
import com.fenxiangle.yueding.feature.mine.view.RechargeCreditActivity;
import com.fenxiangle.yueding.feature.mine.view.adapter.PublishDemandAdapter;
import com.fenxiangle.yueding.feature.mine.view.adapter.VedioAdapter;
import com.fenxiangle.yueding.feature.order.contract.OrderContract;
import com.fenxiangle.yueding.feature.order.dependencies.order.DaggerOrderComponent;
import com.fenxiangle.yueding.feature.order.dependencies.order.OrderPresenterModule;
import com.fenxiangle.yueding.feature.order.view.adapter.ReceiveAdapter;
import com.fenxiangle.yueding.feature.publish.contract.PublishContract;
import com.fenxiangle.yueding.framework.api.HomeApi;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.flyco.tablayout.utils.UnreadMsgUtils;
import com.flyco.tablayout.widget.MsgView;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.luck.picture.lib.rxbus2.ThreadMode;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseFragment;
import com.suozhang.framework.utils.logger.Logger;
import com.suozhang.framework.widget.EmptyView;
import com.suozhang.framework.widget.SpacesItemDecoration;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.leolin.shortcutbadger.ShortcutBadger;

/**
 * A simple {@link Fragment} subclass.
 */
public class ReceiveOrderFragment extends BaseFragment implements OrderContract.View, OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    @BindView(R.id.tl_6)
    CommonTabLayout tl6;
    @BindView(R.id.rv_receive_order)
    RecyclerView rvReceiveOrder;
    @BindView(R.id.smartRefesh)
    SmartRefreshLayout mSmartRefesh;

    private String[] mTitles = {"抢单", "邀约单"};
    private ArrayList<CustomTabEntity> mTabEntities;
    private ReceiveAdapter mAdapter;


    private EmptyView mEmptyView;
    private int pageIndex = 1;
    private int pageSize = 10;
    List<PublishDemandBo> mData;
    private Integer mType = 1;
    @Inject
    OrderContract.Presenter mPresenter;

    CallBackValue callBackValue;

    /**
     * fragment与activity产生关联是  回调这个方法
     */
    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        //当前fragment从activity重写了回调接口  得到接口的实例化对象
        callBackValue =(CallBackValue) getActivity();
    }


    @Override
    public int attachLayoutRes() {
        return R.layout.fragment_receive_order;
    }

    @Override
    protected void initInjector() {
        DaggerOrderComponent.builder().orderPresenterModule(new OrderPresenterModule(this)).build().inject(this);
    }

    @Override
    public void toComments(String s) {

    }

    @Override
    public void confirmOrder(String s) {

    }

    @Override
    public void showUserListSuccess(List<TeamBo> workBoPageData) {

    }

    @Override
    public void showSheetSuccess(UserImageBo workBoPageData) {
        showMsg("抢单成功！");
        mSmartRefesh.autoRefresh();
        callBackValue.SendMessageValue(true);
        RxBus.getDefault().post(new EventEntity(999));
    }

    @Override
    public void showcancleSheetSuccess(UserImageBo workBoPageData) {
        showMsg("取消抢单成功！");
        mSmartRefesh.autoRefresh();
        callBackValue.SendMessageValue(true);
        RxBus.getDefault().post(new EventEntity(999));
    }

    @Override
    public void showPublishListSuccess(List<PublishDemandBo> workBoPageData) {
        mSmartRefesh.finishRefresh();
        mAdapter.setType(2);
        mData = workBoPageData;
        setData(true, mData);
        mAdapter.setEnableLoadMore(true);
    }

    //抢单
    @Override
    public void showSheetListSuccess(List<PublishDemandBo> workBoPageData) {
        mAdapter.setType(1);
        mSmartRefesh.finishRefresh();
        mData = workBoPageData;
        setData(true, mData);
        mAdapter.setEnableLoadMore(true);
    }


    @Override
    public void showPublishListError(String error) {
        if (mSmartRefesh != null) mSmartRefesh.finishRefresh();
        mAdapter.setEmptyView(mEmptyView.getErrorView(error));
        mAdapter.setNewData(null);
        mAdapter.setEnableLoadMore(true);
        mSmartRefesh.finishRefresh();
    }

    @Override
    public void showPublishListMoreSuccess(List<PublishDemandBo> msg) {
        setData(false, msg);
    }

    @Override
    public void showPublishListMoreError(String msg) {
        mAdapter.loadMoreFail();
    }

    @Override
    public void showPublishListEmpty() {
        if (mSmartRefesh != null) mSmartRefesh.finishRefresh();
        mAdapter.setEmptyView(mEmptyView.getEmptyView());
        mAdapter.setNewData(null);
    }

    @Override
    public void showAcceptSuccess(String s) {
        showMsg("接单成功！");
        mSmartRefesh.autoRefresh();
        callBackValue.SendMessageValue(true);
        RxBus.getDefault().post(new EventEntity(999));

    }

    @Override
    public void showInsufficientBalance() {
        startActivity(new Intent(getActivity(), RechargeCreditActivity.class));
    }

    @Override
    public void showRefuseSuccess(String s) {
        showMsg("拒单成功！");
        mSmartRefesh.autoRefresh();

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBus(EventEntity obj) {
        switch (obj.what) {
            case 999:
            case 55:
                mSmartRefesh.autoRefresh();
                break;
        }
    }

    @Override
    public void showError(String error) {
        showMsg(error);
    }

    @Override
    public void showConfrimTxSuccess() {

    }

    @Override
    public void showAppealTxSuccess(String s) {

    }

    @Override
    public void showCancleSuccess() {

    }

    public void initAdapter() {
        mSmartRefesh.setEnableLoadMore(false);
        mSmartRefesh.setOnRefreshListener(this);
        mEmptyView = new EmptyView(rvReceiveOrder);
        rvReceiveOrder.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new ReceiveAdapter();
        mAdapter.bindToRecyclerView(rvReceiveOrder);
        mAdapter.setOnLoadMoreListener(this, rvReceiveOrder);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void initView() {



        if (!RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().register(this);
        }
        mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i]));
        }
        tl6.setTabData(mTabEntities);
        initAdapter();
    }

    @Override
    protected void initData() {
        pageIndex = 1;
        if(mType==1){
            mPresenter.sheetList(pageIndex, pageSize);
        }else{
            mPresenter.getPublishInviteList(pageIndex, pageSize, 2);


        }        callBackValue.sendSelectCount(true);
        getMsgCount();
    }

    @Override
    protected void initEvent() {
        tl6.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                pageIndex=1;

                if (position==0){
                    mType =1;
                    mPresenter.sheetList(pageIndex, pageSize);
                }else {
                    mType =2;
                    mPresenter.getPublishInviteList(pageIndex, pageSize, 2);

                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

    }

    private void setData(boolean isRefresh, List data) {
        pageIndex++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < pageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refresh();
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }


    private void refresh() {
        mAdapter.setEnableLoadMore(false);
        initData();
    }

    private void loadMore() {
        if(mType==1){
            mPresenter.sheetList(pageIndex, pageSize);

        }else{
            mPresenter.getPublishInviteListMore(pageIndex, pageSize, 2);

        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.btn_my_publish_cancle:
                mPresenter.refuseOrder(mData.get(position).getOrderId());
                break;
            case R.id.btn_my_publish_confrim:
                if(mType==1){//接单
                    if(mData.get(position).getGrabStatus()==0){//没有抢单
                        mPresenter.sheet(mData.get(position).getOrderId());
                    }else{
                        //取消抢单
                        mPresenter.cancelSheet(mData.get(position).getOrderId());
                    }

                }else{//抢单
                    mPresenter.acceptOrder(mData.get(position).getOrderId());
                }
                break;

            case R.id.iv_my_publish_head:
            case R.id.tv_my_publish_username:
                Intent intent = new Intent(getActivity(), UserInfoActivity.class);
                intent.putExtra("id", mData.get(position).getUserUid());
                startActivity(intent);
                break;
        }
    }


    //定义一个回调接口
    public interface CallBackValue{
        public void SendMessageValue(boolean isStall);

        public void sendSelectCount(boolean isSelect);
    }


    private void getMsgCount() {
        AM.api().createApiService(HomeApi.class)
                .selectDiffMessageCount(new UnMsgBo(3 + ""))
                .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                .subscribe(new Observer<UnReadCountBo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UnReadCountBo msgBos) {
                        if (msgBos != null) {
                            if (msgBos.getMyAcceptGeneralWaitingAccept() > 0) {
                                tl6.showMsg(0, msgBos.getMyAcceptGeneralWaitingAccept());
                                tl6.setMsgMargin(0, -3, 2);
                                MsgView rtv_2_3 = tl6.getMsgView(0);
                                if (rtv_2_3 != null) {
                                    rtv_2_3.setStrokeColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_3.setBackgroundColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_3.setTextColor(getResources().getColor(R.color.bg_060000));
                                    rtv_2_3.setTextSize(10);
                                    DisplayMetrics dm = rtv_2_3.getResources().getDisplayMetrics();
                                    int size = (int) (14 * dm.density);
                                    UnreadMsgUtils.setSize(rtv_2_3,size);
                                }
                            }else {
                                tl6.hideMsg(0);
                            }
                            if (msgBos.getMyAcceptInviteWaitingAccept() > 0) {
                                tl6.showMsg(1, msgBos.getMyAcceptInviteWaitingAccept());
                                tl6.setMsgMargin(1, -3, 2);
                                MsgView rtv_2_3 = tl6.getMsgView(0);
                                if (rtv_2_3 != null) {
                                    rtv_2_3.setStrokeColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_3.setBackgroundColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_3.setTextColor(getResources().getColor(R.color.bg_060000));
                                    rtv_2_3.setTextSize(10);
                                    DisplayMetrics dm = rtv_2_3.getResources().getDisplayMetrics();
                                    int size = (int) (14 * dm.density);
                                    UnreadMsgUtils.setSize(rtv_2_3,size);
                                }
                            }else {
                                tl6.hideMsg(1);
                            }
                            if(msgBos.getUserCenterTotal()>0){
                                ShortcutBadger.applyCount(getActivity(), msgBos.getUserCenterTotal());
                            }else {
                                ShortcutBadger.removeCount(getActivity());
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
